package com.ctec.dataprocess.txt;

import com.alibaba.fastjson2.JSON;
import com.ctec.FileService;
import com.ctec.asset.AssetPassword;
import com.ctec.mapper.AssetPasswordMapper;
import com.ctec.service.AssetPasswordService;
import com.ctec.util.R;
import com.ctec.vo.DataIntegrationForm;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.*;
import java.util.regex.Pattern;


@RequestMapping("txt")
@RestController
@Slf4j
@Tag(name = "数据引接")
public class ProcessTxt {

    /**
     * 接口测试txt数据解析入库
     */

    @GetMapping("process")
    public String process(@RequestParam String path) {

        // 提取前100行数据
        StringBuilder stringBuilder = new StringBuilder();
        int count = 100;

        try {
            // 创建一个FileReader对象，用于读取文件
            FileReader fileReader = new FileReader(path);
            // 创建一个BufferedReader对象，用于缓冲读取文件内容
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            // 逐行读取文件内容，直到读取到文件末尾（readLine()返回null）
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                parseData(line); // 按行去解析数据
                if (count-- > 0) {
                    stringBuilder.append(line).append("\n");
                }
            }
            // 关闭BufferedReader和FileReader，释放资源
            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    @Resource
    private AssetPasswordService assetPasswordService;

    private static List<AssetPassword> list = new ArrayList<>();

    private void parseData(String line) {
        String[] split = line.split(":");
        if (split.length == 2) {

            if (list.size() >= 1000) {
                assetPasswordService.saveBatch(list);
                list.clear();
            }
            // System.out.println(split);
            AssetPassword assetPassword = new AssetPassword();
            assetPassword.setPassword(split[1]);
            assetPassword.setName(split[0]);
            assetPassword.setRecordingTime(new Date());
            list.add(assetPassword);
            // assetPasswordMapper.insert(assetPassword);
        } else {
            System.out.println(line);
            log.error("这行数据解析存在问题：{}", line);
        }
    }

    @Operation(summary = "根据类型拿到预设字段")
    @GetMapping("getField")
    public R getFileds(@RequestParam String type) {
        List<String> field = switch (type) {
            case "密码" -> {
                yield List.of("name", "password", "type");
            }
            case "知识库" -> {
                yield List.of("name", "password", "type");
            }
            default -> {
                yield List.of();
            }
        };
        return R.ok(field);

    }


    @Resource
    private FileService fileService;


    @Operation(summary = "新建数据引接任务")
    @PostMapping("createDataIntegration")
    public R createDataIntegration(@RequestBody DataIntegrationForm dataIntegrationForm) {

        new Thread(() -> {
            try {
                InputStream inputStream = fileService.downloadFile("test", dataIntegrationForm.getFilePath());

                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                // 逐行读取文件内容，直到读取到文件末尾（readLine()返回null）
                while ((line = bufferedReader.readLine()) != null) {
                    buildObject(line, dataIntegrationForm.getSeparator(), dataIntegrationForm.getMap()); // 提取方法，ctrl alt m
                }
                // 关闭BufferedReader和FileReader，释放资源
                bufferedReader.close();
                inputStreamReader.close();



                // // 创建一个FileReader对象，用于读取文件
                // FileReader fileReader = new FileReader(dataIntegrationForm.getFilePath());
                // // 创建一个BufferedReader对象，用于缓冲读取文件内容
                // BufferedReader bufferedReader = new BufferedReader(fileReader);
                // String line;
                // // 逐行读取文件内容，直到读取到文件末尾（readLine()返回null）
                // while ((line = bufferedReader.readLine()) != null) {
                //     buildObject(line, dataIntegrationForm.getSeparator(), dataIntegrationForm.getMap()); // 提取方法，ctrl alt m
                // }
                // // 关闭BufferedReader和FileReader，释放资源
                // bufferedReader.close();
                // fileReader.close();


            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();


        return R.ok("开始引接");

    }



    // 半自动
    @GetMapping("manualMapping")
    public String manualMapping() {

        String separator = "\\|";  // 用户填入分隔符

        String filePath = "D:\\密码\\TIGERAIRTW\\sso.txt";  // 需要处理的文件路径

        List<String> fields = new ArrayList<>();  // 数据库字段
        fields.add("name");
        fields.add("password");
        fields.add("type");

        List<String> jdk9CollectionFactory = List.of("name", "password", "type");


        Map<Integer, String> map = new HashMap<>();
        map.put(5, "name");
        map.put(3, "password");  // 用户手动映射字段

        Map<Integer, String> jdk11Map = Map.of(5, "name", 3, "password");


        //     开始处理数据

        return "success";
    }

    private static void buildObject(String line, String separator, Map<String, String> map) {
        String[] split = line.split(Pattern.quote(separator));
        HashMap<String, String> objectBuilder = new HashMap<>();
        for (String i : map.keySet()) {
            objectBuilder.put(map.get(i), split[Integer.parseInt(i)-1]);
        }
        AssetPassword assetPassword = JSON.parseObject(JSON.toJSONString(objectBuilder), AssetPassword.class);
        System.out.println(assetPassword);
    }

}
